package com.rc.saas.tenant.controller.order;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.constant.CommonConstant;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.hlht.*;
import com.rc.saas.tenant.model.hlhtsk.HlhtskTenant;
import com.rc.saas.tenant.model.invoice.InvoiceOrder;
import com.rc.saas.tenant.model.operator.RcOperator;
import com.rc.saas.tenant.model.order.OrderInfoExample;
import com.rc.saas.tenant.model.tenant.*;
import com.rc.saas.tenant.search.order.HlhtOrderInfoSearch;
import com.rc.saas.tenant.search.order.OrderInfoStatisticsSearch;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.hlht.HlhtOperatorService;
import com.rc.saas.tenant.service.hlht.HlhtTenantOpenService;
import com.rc.saas.tenant.service.hlhtsk.HlhtskTenantService;
import com.rc.saas.tenant.service.invoice.InvoiceOrderService;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.service.tenant.TenantCompanyInfoService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.util.PubFetchTool;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.StdRequest;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.elec.ElecGun;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.order.OrderInfo;
import com.rc.saas.tenant.search.order.OrderSearch;
import com.rc.saas.tenant.search.order.OrderTotalDataSearch;
import com.rc.saas.tenant.service.elec.ElecGunService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.hlht.HlhtTenantVo;
import com.rc.saas.tenant.vo.order.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author frog
 * @date 2019/10/10
 */
@Controller
@RequestMapping("/orderInfo")
public class OrderInfoController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private HlhtskTenantService hlhtskTenantService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private RedisLoader redisLoader;

    @Autowired
    private HlhtOperatorService hlhtOperatorService;

    @Autowired
    private HlhtTenantOpenService hlhtTenantOpenService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantCompanyInfoService tenantCompanyInfoService;

    @Autowired
    private RcOperatorService operatorService;

    @Autowired
    private TenantRoleService tenantRoleService;

    /**
     * 跳转订单页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String orderInfoPage(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantRole role = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        List<RcOperator> operatorInfos= operatorService.loadOperator(user.getLoginName());
      /*  List<TenantCompanyInfo> tenantCompanyInfos = tenantCompanyInfoService.listByTenantCode(user.getTenantCode());
        model.addAttribute("tenantCompanyInfos", tenantCompanyInfos);*/
        model.addAttribute("operatorInfos", operatorInfos);
        model.addAttribute("userType", CommonConstant.TENANT_CODE);
        model.addAttribute("user", user);
        model.addAttribute("role", role);
        return "/templates/order/orderInfo/orderInfo";

    }

    /**
     * 返回订单列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listOrderInfo", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listOrderInfo(OrderSearch orderSearch) {
        TenantUser user = ShiroUtils.getSessionUser();
        orderSearch.setLoginName(user.getLoginName());
        PageInfo<OrderResult> pageInfo = orderInfoService.listPageByCondition(orderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转分销商订单页面
     *
     * @return
     */
    @RequestMapping(value = "/operator/index", method = RequestMethod.GET)
    public String operatorOrderInfoPage(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        model.addAttribute("user", user);
        return "/templates/order/orderInfo/operatorOrderInfo";
    }

    /**
     * 批量删除
     *
     * @return
     */
    @RequestMapping(value = "/deleteOrderIds", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteOrderIds(String orderIds) {
        if (orderIds.startsWith(",")){
            orderIds = orderIds.substring(1,orderIds.length());
        }
        String[] strs = orderIds.split(",");
        List<Long> orderInfoIds = Arrays.stream(strs).map(str -> Long.parseLong(str.trim())).collect(Collectors.toList());
        OrderInfoExample orderInfoExample = new OrderInfoExample();
        orderInfoExample.createCriteria().andOrderIdIn(orderInfoIds);
        List<OrderInfo> delLstInfo = orderInfoService.selectByExample(orderInfoExample);
        for (int i = 0; i <delLstInfo.size() ; i++) {
            delLstInfo.get(i).setIsDelete("1");
            orderInfoService.updateByPrimaryKey(delLstInfo.get(i));
        }

        return TResponse.SUCCESS();
    }

    /**
     * 返回分销商订单列表数据
     *
     * @return
     */
   /* @RequestMapping(value = "/listPageOperatorOrderInfo", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageOperatorOrderInfo(OrderSearch orderSearch) {

        TenantUser user = ShiroUtils.getSessionUser();
        orderSearch.setTenantOperatorCode(user.getTenantOperatorCode());
        PageInfo<OrderResult> pageInfo = orderInfoService.listPageOperatorOrderInfo(orderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }*/


    /**
     * 导出订单列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(OrderSearch orderSearch, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(orderSearch);
            PageInfo<OrderResult> pageInfo = orderInfoService.listPageByCondition(orderSearch);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderResult.class).sheet("订单列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出订单列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * 导出分销商订单列表
     */
   /* @ResponseBody
    @RequestMapping("/exportOperatorOrderInfo")
    public void exportOperatorOrderInfo(OrderSearch orderSearch, HttpServletResponse response) {
        if (orderSearch.getCount() == 0 || orderSearch.getCount() == null) {
            orderSearch.setCount(orderSearch.getLimit());
        }
        if (orderSearch.getCount() > 50000) {
            orderSearch.setCount(50000);
        }

        //导出拼接开始条数
        orderSearch.setOffset(orderSearch.getLimit() * (orderSearch.getOffset() - 1));
        TenantUser user = ShiroUtils.getSessionUser();
        orderSearch.setTenantOperatorCode(user.getTenantOperatorCode());
        List<OrderPrintVo> orderPrintVos = orderInfoService.listOperatorOrderInfo(orderSearch);
        try {

            logger.info(orderSearch.getTenantCode() + ",orderInfo/exportOperatorOrderInfo,startTime:{},endTime:{},count:{}",
                    orderSearch.getStartTime(), orderSearch.getEndTime(), orderSearch.getCount());

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderPrintVo.class).sheet("订单列表").doWrite(orderPrintVos);
        } catch (Exception e) {
            logger.error("导出订单失败", e.getMessage());
        }
    }*/

    /**
     * 跳转财务管理-财务统计页面
     *
     * @return
     */
    @RequestMapping(value = "/totalDataIndex", method = RequestMethod.GET)
    public String totalDataIndex(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();

        Tenant tenant = tenantService.selectByPrimaryKey(user.getTenantCode());

        Set<String> tenantCodes = new HashSet();
        List operatorIds = new LinkedList();
        //内部互联
        HlhtTenantOpenExample tenantExample1 = new HlhtTenantOpenExample();
        tenantExample1.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andStatusEqualTo("1").andHlhtTypeEqualTo("1");
        List<HlhtTenantOpen> hlhtTenantOpens = hlhtTenantOpenService.selectByExample(tenantExample1);

        for (HlhtTenantOpen hlhtTenantOpen : hlhtTenantOpens) {
            if (StringUtil.isNotBlank(hlhtTenantOpen.getHlhtTenantCode())) {
                tenantCodes.add(hlhtTenantOpen.getHlhtTenantCode());
            }
            if (StringUtil.isNotBlank(hlhtTenantOpen.getHlhtOperatorId())) {
                operatorIds.add(hlhtTenantOpen.getHlhtOperatorId());
            }
        }

        HlhtTenantOpenExample tenantExample2 = new HlhtTenantOpenExample();
        tenantExample2.createCriteria().andHlhtTenantCodeEqualTo(user.getTenantCode()).andStatusEqualTo("1").andHlhtTypeEqualTo("0");
        List<HlhtTenantOpen> hlhtTenantOpens1 = hlhtTenantOpenService.selectByExample(tenantExample2);

        for (HlhtTenantOpen hlhtTenantOpen : hlhtTenantOpens1) {
            tenantCodes.add(hlhtTenantOpen.getTenantCode());
        }

        List<String> result = new ArrayList<>(tenantCodes);
        List<Tenant> tenantList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(result)) {
            TenantExample tenantExample = new TenantExample();
            tenantExample.createCriteria().andTenantCodeIn(result);
            tenantList = tenantService.selectByExample(tenantExample);
        }

        List<HlhtOperator> hlhtOperators = new ArrayList<>();

        if (!CollectionUtils.isEmpty(operatorIds)) {
            HlhtOperatorExample example = new HlhtOperatorExample();
            example.createCriteria().andHlhtOperatorIdIn(operatorIds);
            hlhtOperators = hlhtOperatorService.selectByExample(example);
        }

        List<TenantCompanyInfo> tenantCompanyInfos = tenantCompanyInfoService.listByTenantCode(user.getTenantCode());
        model.addAttribute("tenantCompanyInfos", tenantCompanyInfos);

        model.addAttribute("tenant", tenant);
        model.addAttribute("tenantList", tenantList);
        model.addAttribute("hlhtOperators", hlhtOperators);

        return "/templates/order/totalData/totalData";
    }

    /**
     * 跳转财务管理-正向内部外联订单财务统计页面
     *
     * @return
     */
    @RequestMapping(value = "/totalSaasDataIndex", method = RequestMethod.GET)
    public String totalSaasDataIndex(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();

        HlhtTenantOpenExample hlhtTenantOpenExample = new HlhtTenantOpenExample();
        hlhtTenantOpenExample.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andHlhtTypeEqualTo("0").andHlhtTypeEqualTo("0");
        List<String> hlhtOperatorIds = hlhtTenantOpenService.selectByExample(hlhtTenantOpenExample).stream().map(hlhtTenantOpen -> hlhtTenantOpen.getHlhtOperatorId()).distinct().collect(Collectors.toList());
        HlhtOperatorExample hlhtOperatorExample = new HlhtOperatorExample();
        hlhtOperatorExample.createCriteria().andHlhtOperatorIdIn(hlhtOperatorIds);
        List<HlhtOperator> hlhtOperators = hlhtOperatorService.selectByExample(hlhtOperatorExample);
        TenantExample tenantExample = new TenantExample();
        List<Tenant> tenants = tenantService.selectByExample(tenantExample);

        model.addAttribute("tenantList", tenants);
        model.addAttribute("hlhtOperators", hlhtOperators);

        return "/templates/order/totalData/saasTotalData";
    }

    /**
     * 返回财务统计数据
     *
     * @return
     */
   /* @RequestMapping(value = "/listTotalData", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listTotalData(OrderTotalDataSearch orderTotalDataSearchVo) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (StringUtil.isNotBlank(orderTotalDataSearchVo.getEquipmentHlhtOperatorId())) {
            if ("tenantCode".equals(orderTotalDataSearchVo.getEquipmentHlhtOperatorId())) {
                orderTotalDataSearchVo.setUserTenantCode(user.getTenantCode());
            } else {
                HlhtOperator hlhtOperator = hlhtOperatorService.selectByPrimaryKey(orderTotalDataSearchVo.getEquipmentHlhtOperatorId());
                if (hlhtOperator != null) {
                    orderTotalDataSearchVo.setEquipmentOperatorId(hlhtOperator.getHlhtOperatorId());
                }

                Tenant tenant = tenantService.selectByPrimaryKey(orderTotalDataSearchVo.getEquipmentHlhtOperatorId());
                if (tenant != null) {
                    orderTotalDataSearchVo.setEquipmentTenantCode(tenant.getTenantCode());
                }
            }
        }

        if (StringUtil.isBlank(orderTotalDataSearchVo.getEndTime())) {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //获取String类型的时间
            orderTotalDataSearchVo.setEndTime(sdf.format(date));
        }


        PageInfo<OrderTotalData> pageInfo = orderInfoService.listPageTotalData1(orderTotalDataSearchVo);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }*/

    /**
     * 返回正向内部外联订单财务统计数据
     *
     * @return
     */
    @RequestMapping(value = "/listSaasTotalData", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listSaasTotalData(OrderTotalDataSearch orderTotalDataSearchVo) {
        if (StringUtil.isBlank(orderTotalDataSearchVo.getEndTime())) {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //获取String类型的时间
            orderTotalDataSearchVo.setEndTime(sdf.format(date));
        }

        PageInfo<SaasOrderTotalData> pageInfo = orderInfoService.listPageSaasTotalData1(orderTotalDataSearchVo);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出财务统计数据
     */
    /*@ResponseBody
    @RequestMapping(value = "/exportTotalData", method = RequestMethod.GET)
    public TResponse exportTotalData(OrderTotalDataSearch orderTotalDataSearchVo, HttpServletResponse response) {

        TenantUser user = ShiroUtils.getSessionUser();
        if (StringUtil.isNotBlank(orderTotalDataSearchVo.getEquipmentHlhtOperatorId())) {
            if ("tenantCode".equals(orderTotalDataSearchVo.getEquipmentHlhtOperatorId())) {
                orderTotalDataSearchVo.setUserTenantCode(user.getTenantCode());
            } else {
                HlhtOperator hlhtOperator = hlhtOperatorService.selectByPrimaryKey(orderTotalDataSearchVo.getEquipmentHlhtOperatorId());
                if (hlhtOperator != null) {
                    orderTotalDataSearchVo.setEquipmentOperatorId(hlhtOperator.getHlhtOperatorId());
                }

                Tenant tenant = tenantService.selectByPrimaryKey(orderTotalDataSearchVo.getEquipmentHlhtOperatorId());
                if (tenant != null) {
                    orderTotalDataSearchVo.setEquipmentTenantCode(tenant.getTenantCode());
                }
            }
        }

        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        if (orderTotalDataSearchVo.getCount() == 0 || orderTotalDataSearchVo.getCount() == null) {
            orderTotalDataSearchVo.setCount(orderTotalDataSearchVo.getLimit());
        }

        if (orderTotalDataSearchVo.getCount() > 150000) {
            return TResponse.FAIL("最多导出十五万数据");
        }

        if (orderTotalDataSearchVo.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //导出拼接开始条数
        orderTotalDataSearchVo.setOffset(orderTotalDataSearchVo.getLimit() * (orderTotalDataSearchVo.getOffset() - 1));

        List<OrderTotalDataPrintVo> list = orderInfoService.exportTotalData(orderTotalDataSearchVo);

        logger.info(orderTotalDataSearchVo.getTenantCode() + ",orderInfo/exportTotalData,startTime:{},endTime:{},count:{}",
                orderTotalDataSearchVo.getStartTime(), orderTotalDataSearchVo.getEndTime(), orderTotalDataSearchVo.getCount());

        try {

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("财务统计数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderTotalDataPrintVo.class).sheet("财务统计数据").doWrite(list);
        } catch (Exception e) {
            logger.error("导出财务统计数据失败", e.getMessage());
        }
        return TResponse.SUCCESS();
    }*/

    /**
     * 导出正向内部外联订单财务统计数据
     */
    @ResponseBody
    @RequestMapping(value = "/exportSaasTotalData", method = RequestMethod.GET)
    public TResponse exportSaasTotalData(OrderTotalDataSearch orderTotalDataSearchVo, HttpServletResponse response) {

        TenantUser user = ShiroUtils.getSessionUser();
        ExportUtils.setDefaultPaging(orderTotalDataSearchVo);

        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        if (orderTotalDataSearchVo.getCount() == 0 || orderTotalDataSearchVo.getCount() == null) {
            orderTotalDataSearchVo.setCount(orderTotalDataSearchVo.getLimit());
        }

        if (StringUtil.isBlank(orderTotalDataSearchVo.getEndTime())) {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //获取String类型的时间
            orderTotalDataSearchVo.setEndTime(sdf.format(date));
        }

        if (orderTotalDataSearchVo.getCount() > 150000) {
            return TResponse.FAIL("最多导出十五万数据");
        }

        if (orderTotalDataSearchVo.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //导出拼接开始条数
        orderTotalDataSearchVo.setOffset(orderTotalDataSearchVo.getLimit() * (orderTotalDataSearchVo.getOffset() - 1));

        List<SaasOrderTotalDataPrintVo> list = orderInfoService.exportSaasTotalData(orderTotalDataSearchVo);

        logger.info(orderTotalDataSearchVo.getTenantCode() + ",orderInfo/exportSaasTotalData,startTime:{},endTime:{},count:{}",
                orderTotalDataSearchVo.getStartTime(), orderTotalDataSearchVo.getEndTime(), orderTotalDataSearchVo.getCount());

        try {

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("Saas第三方财务统计数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SaasOrderTotalDataPrintVo.class).sheet("Saas第三方财务统计数据").doWrite(list);
        } catch (Exception e) {
            logger.error("导出Saas第三方财务统计数据失败", e.getMessage());
        }
        return TResponse.SUCCESS();
    }


    /**
     * 结束订单失败
     *
     * @return
     */
    @RequestMapping(value = "/stopOrderInfo", method = RequestMethod.POST)
    @ResponseBody
    public TResponse stopOrderInfo(Long orderId) {
        try {
            if (orderId == null) {
                return TResponse.FAIL("不存在此订单");
            }

            //互联互通订单类型以tenant_code为基准,0为自主订单 1反向对接订单 2正向对接订单,3,正向内部外联订单 默认0
            OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(orderId);

            ElecStation elecStation = elecStationService.selectByPrimaryKey(orderInfo.getElecStationId());
            TResponse tResponse = TResponse.SUCCESS();
            if (tResponse.getStatus() != 200) {
                return TResponse.FAIL("结束失败:" + tResponse.getMessage());
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("结束订单失败", e.getMessage());
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 小票打印
     *
     * @return
     */
    @RequestMapping(value = "/savePrintReceipt", method = RequestMethod.POST)
    @ResponseBody
    public TResponse savePrintReceipt(Long orderId, String carNum) {

        if (StringUtil.isBlank(carNum)) {
            return TResponse.FAIL("请输入车牌号");
        }
        if (carNum.length() > 10) {
            return TResponse.FAIL("车牌号不能超过十个字符");
        }

        OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(orderId);

        if (orderInfo == null) {
            return TResponse.FAIL("不存在此订单");
        }

        ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfo.getElecGunId());
        if (elecGun == null) {
            return TResponse.FAIL("不存在此枪");
        }


        StartPrintReq startPrintReq = new StartPrintReq();
        startPrintReq.setCarNum(carNum);
        startPrintReq.setStartChargeSeq(orderInfo.getOutOrderNum());

        startPrintReq.setOrderNum(orderInfo.getOrderNum());
        startPrintReq.setConnectorID(elecGun.getGunNo());
        startPrintReq.setOrderId(orderInfo.getOrderId());
        startPrintReq.setPrinterResource("1");
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(orderInfo.getMemberId());

        startPrintReq.setChargeType(memberInfo.getChargeType());

        try {
            //加密
            ObjectMapper objectMapper = new ObjectMapper();
            //dozerMapper.map(startPrintReq,S);
            String enData = objectMapper.writeValueAsString(startPrintReq);
            String jsonData = encryptData(enData, memberInfo.getTenantCode());
            StdRequest tRequest = genSuccessReq(jsonData, memberInfo.getTenantCode());
            TResponse tResponse = TResponse.SUCCESS();
            return tResponse;
        } catch (Exception e) {
            logger.error("query_start_print 失败", e);
            return TResponse.FAIL("处理失败");
        }
    }

    /**
     * 重置小票打印
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/resetPrintReceipt", method = RequestMethod.POST)
    public TResponse resetPrintReceipt(Long orderId) {
        OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(orderId);

        if (orderInfo == null) {
            return TResponse.FAIL("不存在此订单");
        }

        ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfo.getElecGunId());
        if (elecGun == null) {
            return TResponse.FAIL("不存在此枪");
        }


        StartPrintReq startPrintReq = new StartPrintReq();
        startPrintReq.setStartChargeSeq(orderInfo.getOutOrderNum());

        startPrintReq.setOrderNum(orderInfo.getOrderNum());
        startPrintReq.setConnectorID(elecGun.getGunNo());
        startPrintReq.setOrderId(orderInfo.getOrderId());

        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(orderInfo.getMemberId());

        startPrintReq.setChargeType(memberInfo.getChargeType());

        try {
            //加密
            ObjectMapper objectMapper = new ObjectMapper();
            //dozerMapper.map(startPrintReq,S);
            String enData = objectMapper.writeValueAsString(startPrintReq);
            String jsonData = encryptData(enData, memberInfo.getTenantCode());
            StdRequest tRequest = genSuccessReq(jsonData, memberInfo.getTenantCode());
            TResponse tResponse = TResponse.SUCCESS();
            return tResponse;
        } catch (Exception e) {
            logger.error("query_start_print 失败", e);
            return TResponse.FAIL("处理失败");
        }
    }

    /**
     * 跳转至 订单报表统计页面
     *
     * @return
     */
    @RequestMapping(value = "/countOrderInfoPage", method = RequestMethod.GET)
    public String countOrderInfoPage(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<TenantCompanyInfo> tenantCompanyInfos = tenantCompanyInfoService.listByTenantCode(user.getTenantCode());
        model.addAttribute("tenantCompanyInfos", tenantCompanyInfos);
        List<HlhtTenantVo> list = hlhtTenantOpenService.listHlhtTenantByTenantCode(user.getTenantCode());
        model.addAttribute("hlhtTenantList", list);
        return "/templates/order/orderInfo/countOrderInfoPage";
    }

    /**
     * 跳转至 正向内部外联订单报表统计页面
     *
     * @return
     */
    @RequestMapping(value = "/saasCountOrderInfoPage", method = RequestMethod.GET)
    public String saasCountOrderInfoPage(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        HlhtTenantOpenExample hlhtTenantOpenExample = new HlhtTenantOpenExample();
        hlhtTenantOpenExample.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andHlhtTypeEqualTo("0").andHlhtTypeEqualTo("0");
        List<String> hlhtOperatorIds = hlhtTenantOpenService.selectByExample(hlhtTenantOpenExample).stream().map(hlhtTenantOpen -> hlhtTenantOpen.getHlhtOperatorId()).distinct().collect(Collectors.toList());
        HlhtOperatorExample hlhtOperatorExample = new HlhtOperatorExample();
        hlhtOperatorExample.createCriteria().andHlhtOperatorIdIn(hlhtOperatorIds);
        List<HlhtOperator> hlhtOperators = hlhtOperatorService.selectByExample(hlhtOperatorExample);
        TenantExample tenantExample = new TenantExample();
        List<Tenant> tenants = tenantService.selectByExample(tenantExample);

        model.addAttribute("tenantList", tenants);
        model.addAttribute("hlhtOperators", hlhtOperators);
        return "/templates/order/orderInfo/saasCountOrderInfoPage";
    }

    /**
     * 跳转至 分销商订单报表统计页面
     *
     * @return
     */
    @RequestMapping(value = "/tenantOperatorCountOrderInfo", method = RequestMethod.GET)
    public String tenantOperatorCountOrderInfo() {
        return "/templates/order/orderInfo/tenantOperatorCountOrderInfo";
    }

   /* *//**
     * 订单报表统计
     *
     * @return
     *//*
    @ResponseBody
    @RequestMapping(value = "/countOrderInfo", method = RequestMethod.GET)
    public OrderInfoCountVo countOrderInfo(OrderInfoStatisticsSearch orderInfoStatisticsSearch) {
        OrderInfoCountVo orderInfoCountVo = orderInfoService.countOrderInfo(orderInfoStatisticsSearch);
        return orderInfoCountVo;
    }*/

    /**
     * 正向内部外联订单报表统计
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saasCountOrderInfo", method = RequestMethod.GET)
    public SaasOrderInfoCountVo saasCountOrderInfo(OrderTotalDataSearch orderTotalDataSearch) {
        SaasOrderInfoCountVo saasOrderInfoCountVo = orderInfoService.saasCountOrderInfo(orderTotalDataSearch);
        return saasOrderInfoCountVo;
    }


    /**
     * 导出 订单报表统计的相关订单
     */
    /*@ResponseBody
    @RequestMapping(value = "/exportCountOrderInfo", method = RequestMethod.GET)
    public TResponse exportCountOrderInfo(OrderInfoStatisticsSearch orderInfoStatisticsSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        List<OrderInfoCountPrintVo> list = orderInfoService.listCountOrderInfo(orderInfoStatisticsSearch);
        if (list.size() > 50000) {
            return TResponse.FAIL("最多导出五万数据");
        }

        if (list.size() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }
        try {

            logger.info(orderInfoStatisticsSearch.getTenantCode() + ",orderInfo/exportCountOrderInfo,startTime:{},endTime:{},count:{}",
                    orderInfoStatisticsSearch.getStartTime(), orderInfoStatisticsSearch.getEndTime(), orderInfoStatisticsSearch.getCount());

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderInfoCountPrintVo.class).sheet("订单列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出订单失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }*/

    /**
     * 导出 正向内部外联订单报表统计的相关订单
     */
    @ResponseBody
    @RequestMapping(value = "/exportSaasCountOrderInfo", method = RequestMethod.GET)
    public TResponse exportSaasCountOrderInfo(OrderTotalDataSearch orderTotalDataSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        ExportUtils.setDefaultPaging(orderTotalDataSearch);
        List<SaasOrderInfoCountPrintVo> list = orderInfoService.listSaasCountOrderInfo(orderTotalDataSearch);
        if (list.size() > 50000) {
            return TResponse.FAIL("最多导出五万数据");
        }

        if (list.size() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }
        try {

            logger.info(orderTotalDataSearch.getTenantCode() + ",orderInfo/exportSaasCountOrderInfo,startTime:{},endTime:{},count:{}",
                    orderTotalDataSearch.getStartTime(), orderTotalDataSearch.getEndTime(), orderTotalDataSearch.getCount());

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("Saas第三方订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SaasOrderInfoCountPrintVo.class).sheet("Saas第三方订单列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出Saas第三方订单失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * 跳转订单页面(瑞郎要求)
     *
     * @return
     */
    @RequestMapping(value = "/orderContent/{orderId}", method = RequestMethod.GET)
    public String orderContent(@PathVariable("orderId") Long orderId, Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        model.addAttribute("user", user);
        OrderSearch os = new OrderSearch();
        os.setOrderId(orderId);
        List<OrderResult> lst = orderInfoService.listByCondition(os);
        if (lst.size()>0){
            OrderResult or = lst.get(0);
            model.addAttribute("info", or);
            //if (or.)
        }

        return "/templates/order/orderInfo/orderContent";
    }

    /**
     * 根据类型返回互联互通运营商
     * (互联互通订单类型以tenant_code为基准,0为自主订单 1反向对接订单 2正向对接订单, 默认0) 3:内部+反向
     * 瑞晨 : 914401153
     * <p>
     * hlhtType : 互联类型  0:内部互联  1:外部互联  2:政务互联
     *
     * @return
     */
    @RequestMapping(value = "/listHlhtOperator", method = RequestMethod.GET)
    @ResponseBody
    public TResponse listHlhtOperator(String hlhtType, String hlhtOrderType) {
        TenantUser user = ShiroUtils.getSessionUser();

        if (hlhtOrderType == null) {
            return TResponse.FAIL("请选择订单类型");
        }


        if ("1".equals(hlhtOrderType) || "3".equals(hlhtOrderType)) {
            hlhtOrderType = "0";
        } else if ("2".equals(hlhtOrderType)) {
            hlhtOrderType = "1";
        } else if ("0".equals(hlhtOrderType)) {
            return TResponse.SUCCESS_DATA(null);
        }

        HlhtTenantOpenExample example = new HlhtTenantOpenExample();
        example.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andHlhtTypeEqualTo(hlhtOrderType).andHlhtOpenTypeEqualTo(hlhtType);
        List<HlhtTenantOpen> hlhtTenantOpens = hlhtTenantOpenService.selectByExample(example);

        if ("0".equals(hlhtType)) {
            List<String> tenantCodeList = new ArrayList<>();
            for (HlhtTenantOpen hlhtTenantOpen : hlhtTenantOpens) {
                tenantCodeList.add(hlhtTenantOpen.getHlhtTenantCode());
            }

            if ("0".equals(hlhtOrderType)) {
                hlhtOrderType = "1";
            } else if ("1".equals(hlhtOrderType)) {
                hlhtOrderType = "0";
            }

            HlhtTenantOpenExample hlhtTenantOpenExample = new HlhtTenantOpenExample();
            hlhtTenantOpenExample.createCriteria().andHlhtTenantCodeEqualTo(user.getTenantCode()).andHlhtTypeEqualTo(hlhtOrderType).andHlhtOpenTypeEqualTo(hlhtType);
            List<HlhtTenantOpen> hlhtTenantOpens1 = hlhtTenantOpenService.selectByExample(hlhtTenantOpenExample);

            for (HlhtTenantOpen hlhtTenantOpen : hlhtTenantOpens1) {
                tenantCodeList.add(hlhtTenantOpen.getTenantCode());
            }

            if (CollectionUtils.isEmpty(tenantCodeList)) {
                return TResponse.SUCCESS_DATA(null);
            }

            TenantExample tenantExample = new TenantExample();
            tenantExample.createCriteria().andTenantCodeIn(tenantCodeList);
            List<Tenant> tenantList = tenantService.selectByExample(tenantExample);


            return TResponse.SUCCESS_DATA(tenantList);

        } else if ("1".equals(hlhtType) || "2".equals(hlhtType)) {

            List<String> hlhtOperatorIdList = new ArrayList<>();
            for (HlhtTenantOpen hlhtTenantOpen : hlhtTenantOpens) {
                hlhtOperatorIdList.add(hlhtTenantOpen.getHlhtOperatorId());
            }
            if (CollectionUtils.isEmpty(hlhtOperatorIdList)) {
                return TResponse.SUCCESS_DATA(null);
            }
            HlhtOperatorExample hlhtOperatorExample = new HlhtOperatorExample();
            hlhtOperatorExample.createCriteria().andHlhtOperatorIdIn(hlhtOperatorIdList);
            List<HlhtOperator> hlhtOperators = hlhtOperatorService.selectByExample(hlhtOperatorExample);

            return TResponse.SUCCESS_DATA(hlhtOperators);
        }

        return null;
    }

    /**
     * 返回订单详情
     *
     * @return
     */
    @RequestMapping(value = "/selectOrderInfo", method = RequestMethod.GET)
    @ResponseBody
    public TResponse selectOrderInfo(Long orderId) {
        if (orderId == null) {
            return TResponse.FAIL("查询订单为空");
        }
        OrderResult orderResult = orderInfoService.selectOrderInfo(orderId);
        if (orderResult == null) {
            return TResponse.FAIL("不存在此订单");
        }
        return TResponse.SUCCESS_DATA(orderResult);
    }

    /**
     * 跳转订单页面
     *
     * @return
     */
    @RequestMapping(value = "/hlhtOrderIndex", method = RequestMethod.GET)
    public String hlhtOrderInfoPage(Model model) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        HlhtTenantOpenExample hlhtTenantOpenExample = new HlhtTenantOpenExample();
        hlhtTenantOpenExample.createCriteria().andTenantCodeEqualTo(tenantUser.getTenantCode()).andHlhtTypeEqualTo("0");
        List<String> hlhtOperatorIds = hlhtTenantOpenService.selectByExample(hlhtTenantOpenExample).stream().map(hlhtTenantOpen -> hlhtTenantOpen.getHlhtOperatorId()).distinct().collect(Collectors.toList());
        HlhtOperatorExample hlhtOperatorExample = new HlhtOperatorExample();
        hlhtOperatorExample.createCriteria().andHlhtOperatorIdIn(hlhtOperatorIds);
        List<HlhtOperator> hlhtOperators = hlhtOperatorService.selectByExample(hlhtOperatorExample);
        TenantExample tenantExample = new TenantExample();
        List<Tenant> tenants = tenantService.selectByExample(tenantExample);
        //用户方
        model.addAttribute("hlhtOperators", hlhtOperators);
        //设备方
        model.addAttribute("tenants", tenants);
        return "/templates/order/orderInfo/hlhtOrderInfo";

    }

    /**
     * 返回正向内部外联订单列表
     *
     * @param hlhtOrderInfoSearch
     * @return
     */
    @RequestMapping(value = "/listHlhtOrderInfo", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listHlhtOrderInfo(HlhtOrderInfoSearch hlhtOrderInfoSearch) {
        PageInfo<OrderResult> pageInfo = orderInfoService.listPageHlhtOrderInfo(hlhtOrderInfoSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出正向内部外联订单
     *
     * @param hlhtOrderInfoSearch
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportHlhtOrderInfo", method = RequestMethod.GET)
    @ResponseBody
    public TResponse exportHlhtOrderInfo(HlhtOrderInfoSearch hlhtOrderInfoSearch, HttpServletResponse response) {

        ExportUtils.setDefaultPaging(hlhtOrderInfoSearch);
        if (hlhtOrderInfoSearch.getCount() == 0 || hlhtOrderInfoSearch.getCount() == null) {
            hlhtOrderInfoSearch.setCount(hlhtOrderInfoSearch.getLimit());
        }

        if (hlhtOrderInfoSearch.getCount() > 150000) {
            return TResponse.FAIL("最多导出十五万数据");
        }

        if (hlhtOrderInfoSearch.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //导出拼接开始条数
        hlhtOrderInfoSearch.setOffset(hlhtOrderInfoSearch.getLimit() * (hlhtOrderInfoSearch.getOffset() - 1));
        List<HlhtOrderInfoPrintVo> list = orderInfoService.exportHlhtOrderInfo(hlhtOrderInfoSearch);
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {

            logger.info(hlhtOrderInfoSearch.getTenantCode() + ",orderInfo/exportHlhtOrderInfo,startTime:{},endTime:{},count:{}",
                    hlhtOrderInfoSearch.getStartTime(), hlhtOrderInfoSearch.getEndTime(), hlhtOrderInfoSearch.getCount());

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("正向内部外联订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), HlhtOrderInfoPrintVo.class).sheet("正向内部外联订单列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出正向内部外联订单列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    /**
     * 封装KyConfig、数据、加密
     *
     * @param respData
     * @param tenantCode
     * @return
     */
    protected String encryptData(String respData, String tenantCode) {
        HlhtskTenant hlhtskTenant = hlhtskTenantService.selectByTenantCode(tenantCode);
        String data = PubFetchTool.genDDEncodeData(hlhtskTenant, respData);
        return data;
    }

    /**
     * 封装请求信息
     *
     * @param data
     * @param tenantCode
     * @return
     */
    protected StdRequest genSuccessReq(String data, String tenantCode) {
        StdRequest resp = new StdRequest();
        resp.setData(data);
        resp.setSeq(tenantCode);
        return resp;
    }


}
